package filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Filter生命周期
 * 1、构遣器方法
 * 2、init 初始化方法
 *     第1、2步，在web工程启动的时候执行(Filter已经创建）
 * 3、doFilter 过滤方法
 *     每次拦截到请求，就会执行
 * 4、destroy销毁
 *     停止web工程的时候，就会执行(停止web工程，也会销毁Filter过滤器)
 */
public class AdminFilter implements Filter {

    public AdminFilter() {
        System.out.println("1、Filter构造器方法AdminFilter()");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("2、Filter的init(FilterConfig filterConfig)初始化");

        /*FilterConfig类的介绍*/
        //获取Filter的名称filter-name内容
        System.out.println("filter-name的值是:" + filterConfig.getFilterName());
        //获取在Filter中配置的init-param初始化参数
        System.out.println("初始化参数username的值是:" + filterConfig.getInitParameter("username"));
        System.out.println("初始化参数url的值是:" + filterConfig.getInitParameter("url"));
        //获取ServletContext对象
        System.out.println(filterConfig.getServletContext());
    }

    /**
     * doFilter方法，专门用于拦截请求（权限检测、事物处理等），过滤响应
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("3、Filter的doFilter()过滤方法");

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;

        HttpSession session = httpServletRequest.getSession();
        Object user = session.getAttribute("user");
        //如果用户没有登入，则跳转到登入界面
        if (user == null) {
            servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest, servletResponse);
        } else {
            //让程序继续向下访问用户的目标资源
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        System.out.println("4、Filter的destroy()销毁方法");
    }
}
